package org.ihelpuoo.db.sql;

import java.sql.SQLException;

import org.ihelpuoo.lang.LoaderException;
import org.ihelpuoo.lang.ObjectUtils;

public class SQLUtils
{
	public static StringBuffer escapeFieldValue(CharSequence s)
	{
		if (null == s)
			return null;
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < s.length(); i++)
		{
			char c = s.charAt(i);
			if (c == '\'')
				sb.append('\'').append('\'');
			else if (c == '\\')
				sb.append('\\').append('\\');
			else
				sb.append(c);
		}
		return sb;
	}

	/*
	private static StringBuffer escapeConditionString(CharSequence s)
	{
		if (null == s)
			return null;
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < s.length(); i++)
		{
			char c = s.charAt(i);
			if (c == '_')
				sb.append('\\').append(c);
			else if (c == '%')
				sb.append('\\').append(c);
			else
				sb.append(c);
		}
		return sb;
	}
	*/

	public static StringBuffer escapteCondition(CharSequence s)
	{
		if (null == s)
			return null;
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < s.length(); i++)
		{
			char c = s.charAt(i);
			if (c == '\'')
				sb.append('\'').append('\'');
			else if (c == '\\')
				sb.append('\\').append('\\');
			else if (c == '_')
				sb.append('\\').append(c);
			else if (c == '%')
				sb.append('\\').append(c);
			else
				sb.append(c);
		}
		return sb;
	}

	public static boolean isNotNeedQuote(Class type)
	{
		if (type == Boolean.class)
			return false;
		if (type.isPrimitive() && "boolean".equals(type.getName()))
			return false;
		return ObjectUtils.isPrimitive(type);
	}

	public static String formatName(CharSequence cs) throws LoaderException
	{
		String name = null;
		if (cs.charAt(0) == '`' || cs.charAt(cs.length() - 1) == '`')
		{
			if (cs.charAt(0) == '`' && cs.charAt(cs.length() - 1) == '`')
			{
				char[] ca = new char[cs.length() - 2];
				for (int i = 0; i < ca.length; i++)
					ca[i] = cs.charAt(i + 1);
				name = String.valueOf(ca);
			}
			else
				throw new LoaderException("Error field name: \"" + cs.toString() + "\"");
		}
		else
			name = cs.toString();
		if (null == name || name.length() == 0)
		{
			throw new LoaderException("Error field name: \"" + cs.toString() + "\"");
		}
		return name;
	}

	public static SQLException wrapSQLException(Throwable t)
	{
		if (t instanceof SQLException)
			return (SQLException)t;
		return new SQLException(t.getMessage());
	}

}
